<template>
  <div>
    <div style="background-color: #ffffff; display: flex; justify-content: space-between; border-bottom: 1px solid #ebebeb">
      <div style="margin-left: 30px">
        <span style="font-size: 12px">节点间纵向距离</span>
        <el-slider size="mini" v-model="range_vertical" :max="80" :min="20" @change="onChangeOptionByCase1"></el-slider>
      </div>
      <div style="margin-right: 30px; margin-top: 5px">
        <el-button v-show="ifComeBack" type="success" size="small" round @click="handleComeBack">返回</el-button>
        <el-button type="success" size="small" round @click="handleQuerySingleCompany">点对点查询</el-button>
        <el-button type="success" size="small" round @click="handleQueryAllCompany">单点查询</el-button>
      </div>
    </div>
    <div ref="myPage" style="height:calc(100vh - 110px)" @click="isShowNodeMenuPanel = false">
      <SeeksRelationGraph ref="seeksRelationGraph" :options="graphOptions">
        <div slot="node" slot-scope="{node}">
          <div style="height:16px; line-height: 16px; border-radius: 30px; cursor: pointer;" @click="handledNode(node, $event)" @contextmenu.prevent.stop="showNodeMenus(node, $event)">
            <p>{{ node.text }}</p>
          </div>
        </div>
      </SeeksRelationGraph>
    </div>
    <div v-show="isShowNodeMenuPanel" :style="{left: nodeMenuPanelPosition.x + 'px', top: nodeMenuPanelPosition.y + 'px' }" style="z-index: 999;padding:10px;background-color: #ffffff;border:#eeeeee solid 1px;box-shadow: 0px 0px 8px #cccccc;position: absolute;">
      <div style="line-height: 25px;padding-left: 10px;color: #888888;font-size: 12px;">对这个节点进行操作：</div>
      <div class="c-node-menu-item" @click.stop="handleEdit">修改</div>
      <div class="c-node-menu-item" @click.stop="handleDelete">删除</div>
    </div>
    <!-- 修改公司弹窗 -->
    <el-dialog :title="title" :visible.sync="dialogShow" width="40%">
      <el-form :model="form" label-width="80px">
        <el-form-item label="公司名称" prop="nodeData">
          <el-input v-model="form.nodeData" size="medium"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="handleEditNode">确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog title="点对点查询公司" :visible.sync="dialogSingleQuery" width="40%" :before-close="dialogSingleClosed">
      <el-form ref="singleForm" :model="querySingleForm" label-width="100px" :rules="ruleSingle" label-position="left">
        <el-form-item label="投资公司" prop="cmhkIdFrom">
          <el-select v-model="querySingleForm.cmhkIdFrom"
            size="medium"
            clearable
            filterable
            :filter-method="filterMethod"
            @visible-change="visibleChange"
            v-el-select-loadmore="loadMore(rangeNumber)"
            class="select"
            @change="selectCompany"
            placeholder="请选择公司">
            <el-option
              v-for="item in options.slice(0, rangeNumber)"
              :key="item.from"
              :label="item.name"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="被投资公司" prop="cmhkIdTo">
          <el-select v-model="querySingleForm.cmhkIdTo"
            size="medium"
            clearable
            filterable
            class="select"
            placeholder="请选择公司">
            <el-option
              v-for="item in companyNameOptionChild"
              :key="item.from"
              :label="item.name"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="handleSearchSingleCompany('singleForm')">确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog title="单点查询公司" :visible.sync="dialoAllQuery" width="40%" :before-close="dialogAllClosed">
      <el-form ref="allForm" :model="queryAllForm" label-width="100px" :rules="ruleAll" label-position="left">
        <el-form-item label="投资公司" prop="to">
          <el-select v-model="queryAllForm.to"
            size="medium"
            clearable
            filterable
            class="select"
            placeholder="请选择公司">
            <el-option
              v-for="item in allCompanyOption"
              :key="item.id"
              :label="item.name"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="handleSearchAllCompany('allForm')">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import SeeksRelationGraph from 'relation-graph'
import { querySingleChart, queryInitChartData, queryShareChartCompany, queryAllChart } from '@/api/modules/shareChart.js'
import { _debounce } from './index.js'
export default {
  name: 'SeeksRelationGraphDemo',
  components: { SeeksRelationGraph },
  data() {
    return {
      showLoading: true,
      isShowCodePanel: false,
      isShowNodeMenuPanel: false,
      nodeMenuPanelPosition: { x: 0, y: 0 },
      graphOptions: {
        allowShowMiniToolBar: true,
        allowSwitchLineShape: true,
        isMoveByParentNode: true,
        'layouts': [
          {
            'label': '纵向',
            'layoutName': 'tree',
            'layoutClassName': 'seeks-layout-center',
            useLayoutStyleOptions: true,
            'defaultExpandHolderPosition': 'right',
            'defaultNodeFontColor': '#fff',
            'defaultNodeShape': 1,
            'defaultNodeWidth': '320',
            'defaultNodeHeight': '18',
            'defaultLineShape': 4,
            'defaultJunctionPoint': 'lr',
            'defaultNodeBorderWidth': 0,
            'from': 'left',
            'centerOffset_x': -100,
            'centerOffset_y': 0,
            'min_per_width': 480,
            'max_per_width': 600,
            'min_per_height': 35,
            'max_per_height': 80
          }
        ]
      },
      dialogShow: false,
      title: '',
      form: {
        nodeData: ''
      },
      currentNode: {},
      range_vertical: 35, // 节点间最小纵向距离默认值

      dialogSingleQuery: false,
      querySingleForm: {
        cmhkIdFrom: '',
        cmhkIdTo: ''
      },
      ruleSingle: {
        cmhkIdFrom: [{ required: true, message: '请输入投资公司', trigger: 'change' }],
        cmhkIdTo: [{ required: true, message: '请输入被投资公司', trigger: 'change' }]
      },
      companyNameOption: [],
      options: [],
      rangeNumber: 10,
      companyNameOptionChild: [],
      ifComeBack: false,

      dialoAllQuery: false,
      queryAllForm: {
        to: ''
      },
      ruleAll: {
        to: [{ required: true, message: '请输入投资公司', trigger: 'change' }]
      },
      allCompanyOption: []
    }
  },
  mounted() {
    this.initData()
    // this.setGraphData()
  },
  directives:{
    'el-select-loadmore':(el, binding) => {
      // 获取element-ui定义好的scroll盒子
      const SELECTWRAP_DOM = el.querySelector(".el-select-dropdown .el-select-dropdown__wrap")
      if(SELECTWRAP_DOM){
        SELECTWRAP_DOM.addEventListener("scroll", function () {
          /**
           * scrollHeight 获取元素内容高度(只读)
           * scrollTop 获取或者设置元素的偏移值,
           *  常用于:计算滚动条的位置, 当一个元素的容器没有产生垂直方向的滚动条, 那它的scrollTop的值默认为0.
           * clientHeight 读取元素的可见高度(只读)
           * 如果元素滚动到底, 下面等式返回true, 没有则返回false:
           * ele.scrollHeight - ele.scrollTop === ele.clientHeight;
           */
          const condition = this.scrollHeight - this.scrollTop <= this.clientHeight
          if (condition) binding.value()
        })
      }
    }
  },
  methods: {
    // setGraphData() {
    //   var data = {
    //     rootId: '0560',
    //     nodes: [
    //       {name: "中国超大型矿砂船投资有限公司", id: "1528"},
    //       {name: "Golden Future Investment Co., Ltd.", id: "0728"},
    //       {name: "明辉投资有限公司", id: "0730"},
    //       {name: "招商轮船油轮控股有限公司", id: "0693"},
    //       {name: "中国超大型矿砂船运输有限公司", id: "1385"},
    //       {name: "Associated Maritime Company Inc.", id: "0708"},
    //       {name: "招商轮船LNG运输投资有限公司", id: "0773"},
    //       {name: "招商轮船散货船控股有限公司", id: "0724"},
    //       {name: "China Merchants Energy Shipping (Singapore) Holding Pte Ltd", id: "0778"},
    //       {name: "Ming Wah Development Inc.", id: "0727"},
    //       {name: "金辉投资有限公司", id: "0709"},
    //       {name: "招商局能源运输投资有限公司", id: "0560"},
    //       {name: "中国能源运输有限公司", id: "1261"},
    //       {name: "明程投资有限公司", id: "0765"}
    //     ],
    //     links: [
    //       {from: "0560", to: "0693", text: "1.0000"},
    //       {from: "0560", to: "0778", text: "1.0000"},
    //       {from: "0560", to: "0773", text: "1.0000"},
    //       {from: "0560", to: "0724", text: "1.0000"},

    //       {from: "0724", to: "0730", text: "1.0000"},
    //       {from: "0724", to: "0727", text: "1.0000"},
    //       {from: "0724", to: "1385", text: "1.0000"},
    //       {from: "0724", to: "0765", text: "1.0000"},
    //       {from: "0724", to: "1528", text: "1.0000"},
          
    //       {from: "1261", to: "0708", text: "1.0000"},
    //       {from: "1261", to: "0728", text: "1.0000"},
          
    //       {from: "0693", to: "0709", text: "1.0000"},
    //       {from: "0693", to: "1261", text: "0.5100"},
    //     ]
    //   }
    //   setTimeout(
    //   function() {
    //     this.showLoading = false
    //     this.$refs.seeksRelationGraph.setJsonData(
    //       data,
    //       (seeksRGGraph) => {
    //         // 这些写上当图谱初始化完成后需要执行的代码
    //       }
    //     )
    //   }.bind(this), 1000)
    // },
    initData() {
      queryInitChartData().then(res => {
        if (res.data.code === '0') {
          const arr = res.data.body.nodes
          arr.forEach(item => {
            item.color = '#409EFF'
          })
          const data = {
            rootId: res.data.body.rootId,
            nodes: arr,
            links: res.data.body.links
          }
          this.$refs.seeksRelationGraph.setJsonData(
            data,
            (seeksRGGraph) => {
              // 这些写上当图谱初始化完成后需要执行的代码
            }
          )
        }
      })
    },
    showNodeMenus(nodeObject, $event) {
      console.log(nodeObject)
      this.currentNode = nodeObject
      var _base_position = this.$refs.myPage.getBoundingClientRect()
      // console.log('showNodeMenus:', $event, _base_position)
      this.isShowNodeMenuPanel = true
      this.nodeMenuPanelPosition.x = $event.clientX - _base_position.x + 300
      this.nodeMenuPanelPosition.y = $event.clientY - _base_position.y + 50
    },
    handleEdit() {
      this.isShowNodeMenuPanel = false
      this.title = '修改'
      this.dialogShow = true
    },
    handleDelete() {
      const id = this.currentNode.id
      this.$refs.seeksRelationGraph.removeNodeById(id)
      this.isShowNodeMenuPanel = false
    },
    handleEditNode() {
      this.currentNode.text = this.form.nodeData
      this.dialogShow = false
      this.form.nodeData = ''
    },
    onChangeOptionByCase1() {
      this.graphOptions.layouts[0].levelDistance = '' // 因为levelDistance的优先级高，所以想要让下面四个选项有效，则需要将levelDistance置空
      this.graphOptions.layouts[0].min_per_height = this.range_vertical
      // this.graphOptions.layouts[0].max_per_height = this.range_vertical[1]
      this.$refs.seeksRelationGraph.setOptions(this.graphOptions, (seeksRGGraph) => {
        // 这些写上当图谱初始化完成后需要执行的代码
        console.log('setOptions:callback:', seeksRGGraph)
        seeksRGGraph.refresh()
      })
    },
    handledNode(node, $event) {
      console.log(node, $event)
    },
    /**
     * 点对点查公司
     */
    handleQuerySingleCompany() {
      this.dialogSingleQuery = true
      // 公司查询
      queryShareChartCompany({ cmhkIdFrom: '' }).then(res => {
        if (res.data.code === '0') {
          this.companyNameOption = res.data.body
        }
      })
    },
    selectCompany(data) {
      const params = {
        cmhkIdFrom: data
      }
      queryShareChartCompany(params).then(res => {
        if (res.data.code === '0') {
          this.companyNameOptionChild = res.data.body
        }
      })
    },
    // 筛选方法
    filterMethod:_debounce(function(filterVal) {
      if(filterVal){
        let filterArr = this.companyNameOption.filter((item) => {
          return item.name.toLowerCase().includes(filterVal.toLowerCase())
        })
        this.options = filterArr
      }else{
        this.options = this.companyNameOption
      }
    }),
    // 下拉框出现时，调用过滤方法
    visibleChange(flag){
      if(flag){
        this.filterMethod()
      }
    },
    loadMore(n) {
      // n是默认初始展示的条数会在渲染的时候就可以获取,具体可以打log查看
      // elementui下拉超过7条才会出滚动条,如果初始不出滚动条无法触发loadMore方法
      return () => (this.rangeNumber += 5) // 每次滚动到底部可以新增条数  可自定义
    },
    handleSearchSingleCompany(formName) {
      this.ifComeBack = true
      this.$refs[formName].validate((valid) => {
        if (valid) {
          querySingleChart(this.querySingleForm).then(res => {
            if (res.data.code === '0') {
              this.resetForm('singleForm')
              this.dialogSingleQuery = false
              const data = {
                rootId: res.data.body.rootId,
                nodes: res.data.body.nodes,
                links: res.data.body.links
              }
              this.$refs.seeksRelationGraph.setJsonData(
                data,
                (seeksRGGraph) => {
                  // 这些写上当图谱初始化完成后需要执行的代码
                }
              )
            }
          })
        } else {
          return false
        }
      })
    },
    /**
     * 单点查公司
     */
    handleQueryAllCompany() {
      this.dialoAllQuery = true
      // 公司查询
      queryShareChartCompany({ cmhkIdFrom: '' }).then(res => {
        if (res.data.code === '0') {
          this.allCompanyOption = res.data.body
        }
      })
    },
    handleSearchAllCompany(formName) {
      this.ifComeBack = true
      this.$refs[formName].validate((valid) => {
        if (valid) {
          queryAllChart(this.queryAllForm).then(res => {
            if (res.data.code === '0') {
              this.resetForm('allForm')
              this.dialoAllQuery = false
              const data = {
                rootId: res.data.body.rootId,
                nodes: res.data.body.nodes,
                links: res.data.body.links
              }
              this.$refs.seeksRelationGraph.setJsonData(
                data,
                (seeksRGGraph) => {
                  // 这些写上当图谱初始化完成后需要执行的代码
                }
              )
            }
          })
        } else {
          return false
        }
      })
    },
    handleComeBack() {
      this.initData()
      this.ifComeBack = false
    },
    dialogSingleClosed() {
      this.resetForm('singleForm')
      this.dialogSingleQuery = false
    },
    dialogAllClosed() {
      this.resetForm('allForm')
      this.dialoAllQuery = false
    },
    resetForm(formName) {
      this.$refs[formName].resetFields()
    }
  }
}
</script>

<!-- Add 'scoped' attribute to limit CSS to this component only -->
<style scoped>
  .c-node-menu-item{
    line-height: 30px;
    padding-left: 10px;
    cursor: pointer;
    color: #444444;
    font-size: 14px;
    border-top:#efefef solid 1px;
  }
  .c-node-menu-item:hover{
    background-color: rgba(66,187,66,0.2);
  }
  .select {
    width: 100%
  }
</style>
<style>
  .el-slider__runway {
    margin: 10px 0;
  }
</style>
